package com.ikun.common.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName DataCopy
 * @Description: 数据拷贝
 * @CreateDate: 2024/4/16 1:50
 */

public class DataCopy {

    /**
     * 对象拷贝
     * @param source
     * @param tClass
     * @return
     * @param <T>
     */
    public static <T> T copyToObj(Object source, Class<T> tClass) {
        if (Objects.isNull(source)) {
            return null;
        }
        try {
            T target = tClass.newInstance();
            BeanUtils.copyProperties(source, target, tClass);
            return target;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    public static void copyToObj(Object source, Object target) {
        if (Objects.isNull(source)) {
            return;
        }

        BeanUtils.copyProperties(source, target);
    }

    /**
     * 集合拷贝
     * @param source
     * @param tClass
     * @return
     * @param <T>
     */
    public static <T> List<T> copyToListObj(List<?> source, Class<T> tClass) {
        if (Objects.isNull(source)) {
            return null;
        }
        List<T> resultList = new ArrayList<>(source.size());
        for (Object obj : source) {
            try {
                T target = tClass.newInstance();
                BeanUtils.copyProperties(obj, target, tClass);
                resultList.add(target);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return resultList;
    }

    /**
     * 拷贝集合 排除空数据集合的情况
     * @param source
     * @param targetList
     * @param tClass
     * @param <T>
     */
    public static <T> void copyToListObj(List<?> source, List<T> targetList, Class<T> tClass) {
        if (Objects.isNull(source) || Objects.isNull(targetList)) {
            return;
        }
        for (Object obj : source) {
            try {
                // 使用反射创建指定类型的对象
                T target = tClass.newInstance();
                BeanUtils.copyProperties(obj, target, tClass);
                targetList.add(target);
            } catch (InstantiationException | IllegalAccessException e) {
                // 处理实例化失败的异常
                e.printStackTrace();
            }
        }

    }
}
